import { HttpContext } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ALLOW_ANONYMOUS } from '@delon/auth';
import { _HttpClient } from '@delon/theme';
import { generateCodeChallenge, generateCodeVerifier } from '@shared';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api/api';
import { PKCE_CLIENT_ID, PKCE_REDIRECT_URI } from 'src/app/shared/constant/common-constant';

@Component({
  selector: 'app-pcke',
  template: ``,
  providers: [],
  standalone: true
})
export class PckeRedirectComponent implements OnInit {
  // 生成CodeVerifier
  // codeVerifier: string = generateCodeVerifier();
  codeVerifier: string | undefined;
  // codeChallenge
  // codeChallenge: string = generateCodeChallenge(this.codeVerifier);
  codeChallenge: string | undefined;
  // 生成state
  // state: string = generateCodeVerifier();

  // 获取地址栏授权码
  code: string | undefined;
  urlState: string | undefined;
  constructor(
    protected http: _HttpClient,
    private msg: NzMessageService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.route.queryParams.subscribe(res => {
      this.code = res['code'] || '';
      this.urlState = res['state'] || '';
      this.codeVerifier = res['codeVerifier'] || '';
      if (this.codeVerifier) {
        this.codeChallenge = generateCodeChallenge(this.codeVerifier);
      }
    });
  }
  ngOnInit(): void {
    if (this.code) {
      const data = new FormData();
      data.append('grant_type', 'authorization_code');
      data.append('client_id', PKCE_CLIENT_ID);
      data.append('redirect_uri', PKCE_REDIRECT_URI);
      data.append('code', this.code);
      data.append('code_verifier', this.codeVerifier || '');
      data.append('state', this.urlState || '');
      this.http
        .post(`${Api.BaseOAuthApi}/token`, data, null, {
          context: new HttpContext().set(ALLOW_ANONYMOUS, true)
        })
        .subscribe({
          next: (res: NzSafeAny) => {
            localStorage.setItem('accessToken', JSON.stringify(res));
            this.router.navigateByUrl('/');
          },
          error: err => {
            this.msg.warning(`请求token失败：${err.data.error || err.message || err.statusText}`);
          }
        });
    } else {
      const state = generateCodeVerifier();
      const url = `${Api.BaseOAuthApi}/authorize?response_type=code&client_id=${PKCE_CLIENT_ID}&redirect_uri=
      ${encodeURIComponent(PKCE_REDIRECT_URI)}&scope=message.write%20message.read&code_challenge=${this.codeChallenge}&code_challenge_method=S256&state=${state}`;
      window.location.href = url;
    }
  }
}
